<?php
/**
 * OrderController.class.php
 * @package Controller
 * @version $Id: IndexController.class.php 1.0 2016-11-07 22:18:13Z $
 */
class OrderController extends BaseController{
    /**
     * 前函数
     */
     public function init(){
         parent::init();
         if(LoginHelper::getUserName() == '' || LoginHelper::getUserId() == 0){
             $this -> redirect($this -> _createUrl('login/index'));
         }
        // 初始化菜单
        return true;
     }

    /**
     * 操作选项管理--页面
     */
     public function indexAction(){
         $this -> display();
     }

    public function listAction(){
        $model = Controller::createMode(BaseController::$default_db,'t_26_order_product_list');
        $model_order = Controller::createMode(BaseController::$default_db,'t_26_order_info');
        $pagesize = 30;
        if($this->get('m') == 'findPersonalDataNotInFlow'){
            $page = $_GET['page']; // get the requested page
            if(!$page){
                $start = 0;
            }else{
                $start = ($page-1) * $pagesize;
            }
            $map = "1=1";
            $sidx = $this->get('sidx');
            $sord = $this->get('sord');
            $searchOper = $this->get('searchOper');
            $searchString = $this->get('searchString');
            $searchField = $this->get('searchField');
            if($searchOper){
                $map .= " and {$searchField} like '%".$searchString."%' ";
            }
            if($sidx && $sord){
                $ord =  " {$sidx} {$sord} ";
            }else{
                $ord = "time desc";
            }
            $list = $model->group("orderid")->where($map)->order($ord)->limit($start,$pagesize)->select();
            $count = $model->count('t_26_order_product_list',1,$map);
            $responce = new stdClass();
            $responce->page = $page;
            $responce->total = round($count/$pagesize);
            $responce->records = $count;
            $i=0;
            foreach($list as $row) {
                $order = $model_order->find($row['orderid']);
                $responce->rows[$i]['orderid'] = $row['orderid'];
                $responce->rows[$i]['cell'] = array(
                    $row['orderid'],
                    $order['insert_dt'],
                    $order['price'],
                    getOrderType($order['handled']),
                    $order['truename'],
                    $order['tel'],
                    $order['client_type']==1?'网站':'小程序',
                );
                $i++;
            }
            echo json_encode($responce);exit;
        } else {
            $this->assign('is_saleing',$model->where(array('state'=>1))->limit(30)->select());
            $this->assign('wait_pay',$model->where(array('handled'=>0))->limit(30)->select());
            $model_product = Controller::createMode(BaseController::$default_db,'t_26_menu');
            $ids = $model_product->execute("SELECT m_id,SUM(total) as total  from t_26_order_product_list where 1=1 GROUP BY m_id ORDER BY SUM(total) DESC limit 50");
            $i = 0;
            foreach($ids as $v){
                $hot_saleing[$i] = $model_product->find($v['m_id']);
                $hot_saleing[$i]['total'] = $v['total'];
                $i++;
            }
            $this->assign('hot_saleing',$hot_saleing);
            $this->assign('preferential_saleing',$model->where(array('m_tag'=>1))->limit(30)->select());
            $this->assign('recent_udpate',$model->order("update_time desc")->limit(30)->select());
            $this -> display();
        }
    }

    /**
     * 订单详情
     */
    public function detailAction(){
        $map['orderid'] = $_GET['orderid'];
        $model_order = Controller::createMode(BaseController::$default_db,'t_26_order_info');
        $model_user = Controller::createMode(BaseController::$default_db,'t_26_yonghuliebiao');
        $orderinfo = $model_order->getOne($map);
        $product_list_model = Controller::createMode(BaseController::$default_db,'t_26_order_product_list');
        $merchandise_model = Controller::createMode(BaseController::$default_db,'t_26_menu');
        $products = $product_list_model->where($map)->select();
        if(is_array($products)){
            foreach($products as $key=>$row ){
                $p = $merchandise_model->field('*')->find(array("m_id"=>$row['m_id']));
                $products[$key] = array_merge($products[$key],$p[0]);
            }
        }
        $userinfo  = $model_user -> getOne("user_id = ".$orderinfo['user_id']);
        $this->assign('data',$orderinfo);
        $this->assign('userinfo',$userinfo[0]);
        $this->assign('products',$products);

        if( $this->get('excel') == 1 ){
            $excel = $this->instance('excel');
            $content = array();
            $content[] = array('配送时间',$orderinfo['deliver_time'],"","");
            $content[] = array('金额',$orderinfo['price'],"","");
            $content[] = array('','',"","");
            $content[] = array('类别','名称','单价', '数量','规格', '小计','备注');
            foreach($products as $row ){
                if($row['tag_name']){
                    $specName = getProductSpecName($row['m_spec']).'-'.$row['tag_name'];
                }else{
                    $specName = getProductSpecName($row['m_spec']);
                }
                $content[] = array(
                    getProductKindNameRecu($row['kind_id']),
                    $row['m_name'],$row['m_price'],
                    $row['total'],
                    $specName,
                    round(g2kilogram($row[total])*$row[price],2),$row['remark']);
            }
            $content[] = array('','',"","");
            $content[] = array('收货人',$orderinfo['truename'],"","");
            $content[] = array('收货地址',$orderinfo['address'],"","");
            $content[] = array('联系电话',$orderinfo['tel'],"","");
            $excel->setData($content);
            $excel->download('商品明细_'.date("Y-m-d").'_'.$orderinfo['truename']);
        } else {
            $this -> display();
        }
    }

    public function virtualCoinAddAction(){
        $model = Controller::createMode(BaseController::$default_db,'t_29_virtual_coin_apply_order');
        if($_POST){
            $data = array(
                'virtual_coin'=>$this->post('amount')*100,
                'remark'=>$this->post('remark'),
                'attach'=>$this->post('attach'),
                's_id'=>LoginHelper::getUserId(),
            );
            if($model->insert($data,true)){
                echo json_encode(array('code'=>200,'msg'=>'添加成功'));exit;
            }
            echo json_encode(array('code'=>201,'msg'=>'添加失败'));exit;
        }else{
            $this->display('virtual_conin_add');
        }
    }

    /**
     * 积分赠送
     */
    public function virtualCoinSendAction(){
        if($_POST){
            $model = Controller::createMode(BaseController::$default_db,'t_26_yonghuliebiao');
            $virtualCoinModel = Controller::createMode(BaseController::$default_db,'t_29_jikubibiandongmingxibiao');
            $virtualCoinSendModel = Controller::createMode(BaseController::$default_db,'t_29_vis_virtual_conin_send_log');
            $user = $data = $model->execute("select * from t_26_yonghuliebiao where mobile='".$this->post('mobile')."' and user_name='".$this->post('name')."'",false);
            if(!$user){
                echo json_encode(array('code'=>201,'该用户不存在，请核对'));exit;
            }else{
                $data = array(
                    'type'=>1,
                    'remark'=>$this->post('remark'),
                    'user_id'=>$user['user_id'],
                    'user_mobile'=>$user['mobile'],
                    'user_name'=>$user['user_name'],
                    'state'=>1,
                    'create_time'=>date("Y-m-d H:i:s"),
                    'limit_supplier_id'=>LoginHelper::getUserId(),
                    'amount'=>$this->post('amount'),
                );
                if($virtualCoinModel->insert($data) && $virtualCoinSendModel->insert($data)){
                    echo json_encode(array('code'=>200,'msg'=>'添加成功'));exit;
                }else{
                    echo json_encode(array('code'=>202,'msg'=>'添加失败'));exit;
                }
            }
        }else{
            $model = Controller::createMode(BaseController::$default_db,'t_29_virtual_coin_apply_order');
            $data = $model->execute("select sum(virtual_coin) as virtual_coin from t_29_virtual_coin_apply_order where s_id=".LoginHelper::getUserId()." and state=3",false);
            $data_sended = $model->execute("select sum(amount) as virtual_coin from t_29_vis_virtual_conin_send_log where limit_supplier_id=".LoginHelper::getUserId(),false);
            $data['virtual_coin_unused'] = $data['virtual_coin'] - $data_sended['virtual_coin'];
            $this->assign('data',$data);
            $this->display('virtual_conin_send');
        }
    }

    public function virtualCoinSendLogAction(){
        $model = Controller::createMode(BaseController::$default_db,'t_29_vis_virtual_conin_send_log');
        $data_sended = $model->execute("select * from t_29_vis_virtual_conin_send_log where limit_supplier_id=".LoginHelper::getUserId(),true);
        $virtual_coin_used = 0;
        foreach($data_sended  as $row){
            $virtual_coin_used+=$row['amount'];
        }
        $this->assign('list',$data_sended);
        $this->assign('virtual_coin_used',$virtual_coin_used);
        $this->display('virtual_conin_send_log');
    }

    public function virtualCoinListAction(){
        $model = Controller::createMode(BaseController::$default_db,'t_29_virtual_coin_apply_order');
        $data = $model->execute("select sum(virtual_coin) as virtual_coin from t_29_virtual_coin_apply_order where s_id=".LoginHelper::getUserId()." and state=3",false);
        $data_sended = $model->execute("select sum(amount) as virtual_coin from t_29_vis_virtual_conin_send_log where limit_supplier_id=".LoginHelper::getUserId(),false);
        $data['virtual_coin_unused'] = $data['virtual_coin'] - $data_sended['virtual_coin'];
        $this->assign('data',$data);
        $this->assign('list',$model->where(array('s_id'=>LoginHelper::getUserId()))->order("create_time desc")->limit(100)->select());
        $this -> display('virtual_conin_list');
    }
}
